package com.googlecode.cnasort.cc.rmi.server.core;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import org.apache.log4j.Logger;
import com.googlecode.cnasort.cc.rmi.common.RMIFileLoaderConnector;

public class RMIFileLoaderConnectorHelper
{
    private static final Logger logger = Logger.getLogger( RMIFileLoaderConnectorHelper.class );
    private RMIFileLoaderConnectorHelper() {}

    private static void waitAndQuit(
        final RMIFileLoaderConnector remoteObject,
        final String                 serverName
        )
    {
        try {
            Thread.sleep( 10 * 1000 );
            }
        catch (InterruptedException e) {
            // Ignore
            }

        try {
            // Unregister ourself
            Naming.unbind( serverName );
            }
        catch (RemoteException | MalformedURLException | NotBoundException e) {
            logger.warn( "Naming.unbind( \"" + serverName + "\" );", e );
            }

        try {
            // Unexport; this will also remove us from the RMI runtime
            UnicastRemoteObject.unexportObject(remoteObject, true);
            }
        catch (NoSuchObjectException e) {
            logger.warn( "UnicastRemoteObject.unexportObject(this, true);", e );
            }

        System.out.println("RMIFileLoaderConnector exiting.");
        //System.exit(0); // TO DO Well, improve this later
    }

    public static void quit(
            final RMIFileLoaderConnector remoteObject,
            final String                 serverName
            )
    {
        new Thread( new Runnable() {
            @Override
            public void run() {
                RMIFileLoaderConnectorHelper.waitAndQuit(remoteObject, serverName);
            }}).start();
    }
}
